import router, { addRoutes } from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// import { useStore } from "vuex"
import store from '@/store'
import { ElLoading, ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'

// 白名单
const WhiteList = ['/login']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const token = getToken()

  if (token) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const userInfo = store.getters.userInfo
      if (userInfo) {
        next()
      } else {
        let loadingInstance = ElLoading.service({
          fullscreen: true,
          text: '路由跳转中'
        })
        try {
          const res = await store.dispatch('user/getUserInfo')
          const accessRoutes = await store.dispatch(
            'permission/setRoutes',
            res.roles
          )
          addRoutes(accessRoutes)
          store.dispatch('tagsView/addAffixTags')

          next({ ...to, replace: true })
        } catch (error) {
          console.log('errorerrorerror', error)
          await store.dispatch('user/resetToken')
          ElMessage.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
        loadingInstance.close()
        loadingInstance = null
      }
    }
  } else {
    if (WhiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
